package com.kangjia.model.m0.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.kangjia.api.ParserReportService;
import com.kangjia.api.ReportApiImpl;
import com.kangjia.general.dao.query.QueryParam;
import com.kangjia.holder.TableContextHolder;
import com.kangjia.jasckson.DataMapper;
import com.kangjia.model.m0.entity.Employee;
import com.kangjia.model.m0.entity.StoreReport;
import com.kangjia.model.m0.entity.ViewStoreReport;
import com.kangjia.model.m0.service.PdfService;
import com.kangjia.model.m0.service.ReportService;
import com.kangjia.util.JsonNodeUtil;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Controller
@Slf4j
public class PringController {

	@Autowired
	private JedisPool jedisPool;
	@Autowired
	private PdfService pdfService;
	@Autowired
	private ReportApiImpl reportApiImpl;
	@Autowired
	private ReportService reportService;
	@Value("${pdf.url}")
	private String pdfUrl;
	
	private static final List<String> headers = new ArrayList<>();
	
	public static Map<String, QueryParam> params = new HashMap<>();
	public static Map<String, Integer> mods = new HashMap<>();

	static {
		headers.add("门店");
		headers.add("报告编号");
		headers.add("姓名");
		headers.add("电话");
		headers.add("店员");
		headers.add("分数");
		headers.add("检测时间");
	}

	@RequestMapping(value = "/a/report/pdf")
	public void pdf(HttpServletResponse response, String uuid) {
		Jedis jedis = jedisPool.getResource();
		String inspectId = null;
//		String name = null;
		try {
			inspectId = jedis.hget(uuid, "inspectId");
//			name = jedis.hget(uuid, "name");
			jedis.del(uuid);
		} finally {
			jedis.close();
		}
		if (StringUtils.isNotBlank(inspectId)) {
			String jsonNode = reportApiImpl.getReport(inspectId);
			ParserReportService service = new ParserReportService(jsonNode, null);
			String uid = service.getValue("uid");
			try {
				response.sendRedirect(String.format(pdfUrl, uid, inspectId));
			} catch (IOException e) {
				log.error("重定向失败", e);
			}
		}
	}
	
	public void pdf(String inspectId, String name, HttpServletResponse response) {
		if (StringUtils.isNotBlank(inspectId)) {
			log.info("报告Id={}, 门店={}", inspectId, name);
			String jsonNode = reportApiImpl.getReport(inspectId);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			pdfService.createPdf(baos, jsonNode, inspectId, name);
			try {
				response.getOutputStream().write(baos.toByteArray());
			} catch (IOException e) {
				
			} finally {
				try {
					baos.close();
				} catch (IOException e) {
					
				}
			}
		} else {
			try {
				response.getOutputStream().write("读取错误".getBytes());
			} catch (IOException e) {
				
			}
		}
	}
	
	@RequestMapping(value = "/a/report/excel", method = RequestMethod.GET)
	@ResponseBody
	public void excel(String uuid, HttpServletResponse response) {
		XSSFWorkbook workbook = new XSSFWorkbook(); // 创建工作簿对象
		XSSFSheet sheet = workbook.createSheet("报告");
		int row = 0;
		XSSFRow rowRowName = sheet.createRow(row++);
		for (int i = 0; i < headers.size(); i++) {
			XSSFCell cellRowName = rowRowName.createCell(i);
			cellRowName.setCellType(CellType.STRING);
			cellRowName.setCellValue(headers.get(i));
		}
		try {
			if (StringUtils.isNotBlank(uuid)) {
				TableContextHolder.mod(TableContextHolder.store, new Long(PringController.mods.get(uuid)), 10L);
				QueryParam param = PringController.params.get(uuid);
				PringController.params.clear();
				if (param != null) {
					List<StoreReport> list = reportService.pager(StoreReport.class, param);
					Calendar cal = Calendar.getInstance();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					for (StoreReport sr : list) {
						Integer storeId = sr.getStorePk().getStoreId();
						sr.setInspectId(sr.getStorePk().getInspectId());
						cal.setTimeInMillis(sr.getCrtime());
						sr.setDateTime(sdf.format(cal.getTime()));
						sr.setStoreId(sr.getStorePk().getStoreId());
						String json = reportApiImpl.get("store", String.valueOf(storeId));
						if (StringUtils.isNotBlank(json)) {
							try {
								JsonNode jsonNode = DataMapper.getInstance().readTree(json);
								sr.setStoreName(JsonNodeUtil.string(jsonNode, "cname"));
								sr.setStoreId(sr.getStorePk().getStoreId());
							} catch (JsonProcessingException e) {
								
							} catch (IOException e) {
								
							}
						}
						Employee e = reportService.getEmployee(sr.getInspectId());
						if (e != null) {
							sr.setEmployeeName(e.getEmployeeName());
						}
						XSSFRow hssfRow = sheet.createRow(row++);
						List<String> l = sr.toCsv();
						for (int i = 0; i < l.size(); i++) {
							XSSFCell cellRowName = hssfRow.createCell(i);
							cellRowName.setCellType(CellType.STRING);
							cellRowName.setCellValue(l.get(i));
						}
					}
				}
			}
			response.setContentType("application/os-stream");
			try {
				response.setHeader("Content-Disposition", "attachment; filename=" + new String("报告".getBytes("utf-8"), "iso8859-1") + ".xlsx");
				workbook.write(response.getOutputStream());
			} catch (IOException e) {
				
			}
		} finally {
			try {
				workbook.close();
			} catch (IOException e) {
				
			}
		}
	}
	
	
	@RequestMapping(value = "/a/full/excel", method = RequestMethod.GET)
	@ResponseBody
	public void excelFull(String uuid, HttpServletResponse response) {
		XSSFWorkbook workbook = new XSSFWorkbook(); // 创建工作簿对象
		XSSFSheet sheet = workbook.createSheet("报告");
		int row = 0;
		XSSFRow rowRowName = sheet.createRow(row++);
		for (int i = 0; i < headers.size(); i++) {
			XSSFCell cellRowName = rowRowName.createCell(i);
			cellRowName.setCellType(CellType.STRING);
			cellRowName.setCellValue(headers.get(i));
		}
		try {
			if (StringUtils.isNotBlank(uuid)) {
				QueryParam param = PringController.params.get(uuid);
				PringController.params.clear();
				if (param != null) {
					List<ViewStoreReport> list = reportService.pager(ViewStoreReport.class, param);
					Calendar cal = Calendar.getInstance();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					for (ViewStoreReport sr : list) {
						cal.setTimeInMillis(sr.getCrtime());
						sr.setDateTime(sdf.format(cal.getTime()));
						String json = reportApiImpl.get("store", String.valueOf(sr.getStoreId()));
						if (StringUtils.isNotBlank(json)) {
							try {
								JsonNode jsonNode = DataMapper.getInstance().readTree(json);
								sr.setStoreName(JsonNodeUtil.string(jsonNode, "cname"));
							} catch (JsonProcessingException e) {
								
							} catch (IOException e) {
								
							}
						}
						Employee e = reportService.getEmployee(sr.getInspectId());
						if (e != null) {
							sr.setEmployeeName(e.getEmployeeName());
						}
						XSSFRow hssfRow = sheet.createRow(row++);
						List<String> l = sr.toCsv();
						for (int i = 0; i < l.size(); i++) {
							XSSFCell cellRowName = hssfRow.createCell(i);
							cellRowName.setCellType(CellType.STRING);
							cellRowName.setCellValue(l.get(i));
						}
					}
				}
			}
			response.setContentType("application/os-stream");
			try {
				response.setHeader("Content-Disposition", "attachment; filename=" + new String("报告".getBytes("utf-8"), "iso8859-1") + ".xlsx");
				workbook.write(response.getOutputStream());
			} catch (IOException e) {
				
			}
		} finally {
			try {
				workbook.close();
			} catch (IOException e) {
				
			}
		}
	}
}
